package com.qingdai.commoditycenter.controller;

import com.alibaba.fastjson2.JSON;
import com.github.yulichang.query.MPJQueryWrapper;
import com.qingdai.business.emuns.Address;
import com.qingdai.business.emuns.Commodity;
import com.qingdai.business.emuns.Order;
import com.qingdai.business.emuns.Shop;
import com.qingdai.business.entities.CommonResult;
import com.qingdai.business.service.*;
import com.qingdai.business.utils.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.checkerframework.checker.units.qual.C;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author LiuZiMing
 * @since 2024-01-26
 */
@RestController
@RequestMapping("/commodity")
@Tag(name = "商品")
public class CommodityController {
    @Resource
    private CommodityService commodityService;
    @Resource
    private CommodityEsService commodityEsService;
    @DubboReference
    private ShopService shopService;
    @DubboReference
    private AddressService addressService;
    @DubboReference
    private OrderService orderService;
    @Resource
    private JwtUtil jwtUtil;

    {
    }

    @PostMapping("/es")
    @Operation(summary = "所有商品存到ES", description = "")
    @Parameters({
//            @Parameter(name = "id", description = "id", required = true),
    })
    private CommonResult<List<Commodity>> addAddressesToES() {
        List<Commodity> allCommodity = commodityService.list();
        Iterable<Commodity> commoditiesIterable = commodityEsService.saveCommodities(allCommodity);
        return new CommonResult<>(200, "所有商品存到ES成功");
    }

    @GetMapping("/rock/xyz")
    @Operation(summary = "rocketMq测试", description = "")
    @Parameters({
//            @Parameter(name = "id", description = "id", required = true),
    })
    private CommonResult<Address> rocketMQ() throws MQClientException, UnsupportedEncodingException, MQBrokerException, RemotingException, InterruptedException {


        return new CommonResult<>(200, "rocketMq测试");
    }

    //获取commodities
    @GetMapping("/all/xyz")
    @Operation(summary = "获取所有商品", description = "获取所有商品")
    @Parameters({
            @Parameter(name = "shopId", description = "店铺id", required = true),
    })
    private CommonResult<List<Commodity>> getCommodities() {
        List<Commodity> list = commodityService.list();
        if (list == null) {
            return new CommonResult<>(400, "无商品");
        }
        return new CommonResult<>(200, "获取所有商品成功", list);

    }

    //根据shopId获取commodities
    @GetMapping("/shopId")
    @Operation(summary = "根据shopId获取商品", description = "根据shopId获取商品")
    @Parameters({
            @Parameter(name = "shopId", description = "店铺id", required = true),
    })
    private CommonResult<List<Commodity>> getCommoditiesByShopId(Integer shopId) {
        Shop shop = shopService.getById(shopId);
        if (shop == null) {
            return new CommonResult<>(400, "店铺id非法");
        }
        MPJQueryWrapper mpjQueryWrapper2 = new MPJQueryWrapper();
        mpjQueryWrapper2.select("*").eq("shop_id", shopId);
        List<Commodity> list = commodityService.list(mpjQueryWrapper2);
        if (list == null) {
            return new CommonResult<>(400, "本店无商品");
        }
        return new CommonResult<>(200, "获取本店所有商品成功", list);

    }

    @PostMapping("/jwt/shopId")
    @Operation(summary = "根据shopId创建新商品", description = "根据shopId创建新商品")
    @Parameters({
//            @Parameter(name = "id", description = "id", required = true),
            @Parameter(name = "title", description = "标题", required = true),
            @Parameter(name = "price", description = "价格", required = true),
            @Parameter(name = "shippingAddressId", description = "发货地址id", required = true),
            @Parameter(name = "describe", description = "描述", required = true),
            @Parameter(name = "shopId", description = "商店id", required = true),
            @Parameter(name = "number", description = "库存", required = true),

    })
    public CommonResult createCommoditiesByJwt(@RequestParam(required = true) String title,
                                               @RequestParam(required = true) Double price,
                                               @RequestParam(required = true) Integer shippingAddressId,
                                               @RequestParam(required = true) String wDescribe,
                                               @RequestParam(required = true) Integer shopId,
                                               @RequestParam(required = true) Integer number,
                                               HttpServletRequest request) {
        CommonResult result = jwtUtil.getUserIdByRequest(request);
        Integer jwtUserId = (Integer) result.getData();
        Shop shop = shopService.getById(shopId);
        Address address = addressService.getById(shippingAddressId);
        if (shop == null || address == null) {
            return new CommonResult<>(400, "店铺id或地址id非法");
        } else if (Objects.equals(shop.getSellerId(), jwtUserId) || Objects.equals(address.getUserId(), jwtUserId)) {
            boolean createResult = commodityService.save(new Commodity(null, title, price, shippingAddressId, wDescribe, shopId, number, 1));
            if (createResult) {
                return new CommonResult(200, "创建商品成功");
            } else {
                return new CommonResult(400, "创建商品失败");
            }
        } else {
            return new CommonResult<>(400, "非本人店铺或地址");
        }
    }

    @PutMapping("/jwt/id")
    @Operation(summary = "根据id更改商品", description = "根据id更改商品")
    @Parameters({
            @Parameter(name = "id", description = "id", required = false),
            @Parameter(name = "title", description = "标题", required = false),
            @Parameter(name = "price", description = "价格", required = false),
            @Parameter(name = "shippingAddressId", description = "发货地址id", required = false),
            @Parameter(name = "wdescribe", description = "描述", required = false),
            @Parameter(name = "shopId", description = "商店id", required = false),
            @Parameter(name = "number", description = "库存", required = false),
    })
    public CommonResult updateCommoditiesByIdAndJwt(@RequestParam(required = false) Integer id,
                                                    @RequestParam(required = false) String title,
                                                    @RequestParam(required = false) Double price,
                                                    @RequestParam(required = false) Integer shippingAddressId,
                                                    @RequestParam(required = false) String wdescribe,
                                                    @RequestParam(required = true) Integer number,
                                                    HttpServletRequest request) {
        CommonResult result = jwtUtil.getUserIdByRequest(request);
        Integer jwtUserId = (Integer) result.getData();
        Commodity commodity = commodityService.getById(id);
        if (commodity == null) {
            return new CommonResult<>(400, "id非法");
        }
        Integer shopId = commodity.getShopId();
        Address address = addressService.getById(shippingAddressId);
        if (address == null) {
            return new CommonResult<>(400, "地址id非法");
        }
        if (!Objects.equals(address.getUserId(), jwtUserId)) {
            return new CommonResult<>(400, "非本人地址");
        }
        boolean updateResult = commodityService.saveOrUpdate(new Commodity(id, title, price, shippingAddressId, wdescribe, shopId, number, 1));
        if (!updateResult) {
            return new CommonResult(400, "修改商品失败");
        }
        return new CommonResult(200, "修改商品成功");
    }


    @DeleteMapping("/jwt/id")
    @Operation(summary = "根据id删除商品", description = "根据id删除商品")
    @Parameters({@Parameter(name = "id", description = "id", required = true),})
    public CommonResult deleteCommoditiesByIdAndJwt(@RequestParam(required = true) Integer id,
                                                    HttpServletRequest request) {
        CommonResult result = jwtUtil.getUserIdByRequest(request);
        Integer jwtUserId = (Integer) result.getData();
        Commodity commodity = commodityService.getById(id);
        if (commodity == null) {
            return new CommonResult<>(400, "id非法");
        }
        Integer shopId = commodity.getShopId();
        Shop shop = shopService.getById(shopId);
        if (Objects.equals(shop.getSellerId(), jwtUserId)) {
            boolean deleteResult = commodityService.removeById(id);
            if (deleteResult) {
                return new CommonResult(200, "删除商品成功");
            } else {
                return new CommonResult(400, "删除商品失败");
            }
        } else {
            return new CommonResult<>(400, "非本人店铺商品");
        }
    }

    @GetMapping("/id")
    @Operation(summary = "根据id获取商品", description = "根据id获取商品")
    @Parameters({@Parameter(name = "id", description = "id", required = true),})
    public CommonResult getCommoditiesById(@RequestParam(required = true) Integer id) {
        Commodity commodity = commodityService.getById(id);
        if (commodity == null) {
            return new CommonResult<>(400, "id非法");
        }
        return new CommonResult(200, "根据id获取商品成功", commodity);
    }

    @GetMapping("/jwt/id/enable")
    @Operation(summary = "根据id上下架商品", description = "根据id上下架商品")
    @Parameters({@Parameter(name = "id", description = "id", required = true),})
    public CommonResult changeCommodityEnableByIdAndJwt(@RequestParam(required = true) Integer id) {
        Commodity commodity = commodityService.getById(id);
        if (commodity == null) {
            return new CommonResult<>(400, "id非法");
        }
        Integer enable = commodity.getEnable() == 1 ? 0 : 1;
        Boolean changeCommodityEnableResult = commodityService.saveOrUpdate(new Commodity(id, null, null, null, null, null, null, enable));
        if (!changeCommodityEnableResult) {
            return new CommonResult<>(400, "根据id上下架商品失败");
        }
        return new CommonResult(200, "根据id上下架商品成功", commodity);
    }

    //获取commodities
    @GetMapping("/jwt/orderId")
    @Operation(summary = "根据orderId获取商品", description = "根据orderId获取商品")
    @Parameters({
            @Parameter(name = "orderId", description = "订单id", required = true),
    })
    private CommonResult<List<Commodity>> getCommoditiesByOrderId(@RequestParam Integer orderId) {
        List<Commodity> list = new ArrayList<>();
        Order order = orderService.getById(orderId);
        String commodityIdListStr = order.getCommodityIdList();
        String[] commodityIdList = commodityIdListStr.split(",");
        for (String id : commodityIdList) {
            Commodity commodity = commodityService.getById(id);
            list.add(commodity);
        }
        return new CommonResult<>(200, "根据orderId获取商品成功", list);

    }

}
